<template>
  <Dialog
    v-model="show"
    @confirm="handleSubmit"
    @close="close"
    :title="title"
    width="600px"
  >
    <LangTabs v-model="lang" />
    <el-form
      :model="formData"
      label-width="120px"
      ref="formRef"
      :rules="rules"
      v-loading="loading"
    >
      <el-form-item v-if="isChild" :label="$t('spec_lists.所属规格')">
        <el-input :value="data?.parentInfo?.['name' + lang]" disabled />
      </el-form-item>
      <el-form-item
        :label="isChild ? $t('spec_lists.规格值名称') : $t('spec_lists.规格名称')"
        :prop="'name' + lang"
        v-for="item in langs"
        :key="item"
        v-show="lang === item"
      >
        <el-input v-model="formData['name' + item]" :placeholder="$t('spec_lists.请输入名称')" />
      </el-form-item>
      <el-form-item :label="$t('spec_lists.排序')" prop="sort" v-if="!isChild">
        <el-input-number v-model="formData.sort" :min="0" style="width: 100%"/>
      </el-form-item>
    </el-form>
  </Dialog>
</template>

<script setup>
import { ref, watch, computed, reactive } from "vue";
import { ElMessage } from "element-plus";
import Dialog from "@/components/dialog.vue";
import Api from "@/config/api/api";
import LangTabs from "@/components/langTabs.vue";
import i18n from "@/i18n";
import { useI18n } from "vue-i18n";

const { locale, t } = useI18n();
const langs = reactive(Object.keys(i18n.global.messages.value));
console.log("langs===", langs);
const lang = ref("ZhCN");
const show = defineModel();
const emit = defineEmits(["success"]);

const props = defineProps({
  data: {
    type: Object,
    default: () => ({}),
  },
});

const loading = ref(false);
const formData = ref({
  specificationId: null,
  sort: 0
});

const title = computed(()=>{
  if(isEdit.value){
    if(isChild.value){
      return t('spec_lists.编辑规格值')
    }
    return t('spec_lists.编辑规格')
  }else{
    if(isChild.value){
      return t('spec_lists.新增规格值')
    }
    return t('spec_lists.新增规格')
  }
})

const rules = ref({
  sort: [
    { required: true, message: t('spec_lists.请输入顺序'), trigger: "blur" },
  ]
});

langs.forEach((item) => {
  rules.value["name" + item] = [
    { required: true, message: t('spec_lists.请输入名称'), trigger: "blur" },
  ];
  formData.value["name" + item] = "";
});

const formRef = ref();
// 判断是否为编辑模式
const isEdit = computed(() => !!props.data.id);

// 判断是否为子规格
const isChild = computed(() => !!props.data.parentId);

// 监听弹窗显示，初始化表单数据
watch(show, async (val) => {
  lang.value = locale.value;
  if (val && props.data) {
    // 深拷贝，避免直接修改props
    formData.value = JSON.parse(JSON.stringify(props.data));
    console.log(1111, formData.value);
  }
});

// 提交表单
const handleSubmit = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        loading.value = true;

        const params = {
          sort: formData.value.sort
        };
        langs.forEach((item) => {
          params["name" + item] = formData.value["name" + item];
        });

        if (isChild.value) {
          params.specificationId = formData.value.parentId;
        }
        let res = null;
        if (isEdit.value) {
          params.id = formData.value.id;

          if (isChild.value) {
            res = await Api.updateSkuSpecificationDetail(params);
          } else {
            res = await Api.updateSkuSpecification(params);
          }
        } else {
          if (isChild.value) {
            res = await Api.addSkuSpecificationDetail(params);
          } else {
            res = await Api.addSkuSpecification(params);
          }
        }
        if (res.status == 200) {
          ElMessage.success(t('spec_lists.保存成功'));
          emit("success");
          close();
        }
      } catch (error) {
        ElMessage.error(error.message || t('spec_lists.保存失败'));
      } finally {
        loading.value = false;
      }
    }
  });
};

// 关闭弹窗
const close = () => {
  formData.value = {
    specificationId: null,
    sort: 0
  };
  langs.forEach((item) => {
    formData.value["name" + item] = "";
  });
  show.value = false;
};
</script>
